<template>
  <div class="p16">
    <van-cell-group inset>
      <van-cell title="今日记录" />
      <van-field v-model="activityTitle" label="事情" placeholder="选择事情" readonly clickable @click="showActivity = true" />
      <van-popup v-model:show="showActivity" round position="bottom">
        <van-picker :columns="activityColumns" @confirm="onPickActivity" @cancel="showActivity=false" />
      </van-popup>
      <van-cell title="数量">
        <template #right-icon>
          <van-stepper v-model="quantity" min="1" />
        </template>
      </van-cell>
      <div style="margin: 12px 16px 0 16px">
        <van-button round block type="primary" @click="addRecord">添加记录</van-button>
      </div>
      <van-cell title="今日合计" :value="String(dayTotal)" />
    </van-cell-group>

    <van-cell-group inset style="margin-top: 16px">
      <template v-if="records.length">
        <van-swipe-cell v-for="r in records" :key="r.id">
          <van-cell :title="`${r.date.slice(0,10)} - ${displayActivity(r.activityTemplateId)}`" :label="`x ${r.quantity} = ${r.points}`" />
          <template #right>
            <van-button square type="danger" text="删除" @click="removeRecord(r.id)" />
          </template>
        </van-swipe-cell>
      </template>
      <van-empty v-else description="暂无记录" />
    </van-cell-group>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { showToast, showConfirmDialog } from 'vant'
import { useChildrenStore } from '@/stores/children'
import dayjs from 'dayjs'
import timezone from 'dayjs/plugin/timezone'
import utc from 'dayjs/plugin/utc'

dayjs.extend(utc)
dayjs.extend(timezone)

const children = useChildrenStore()
const activityTemplates = ref<any[]>([])
const records = ref<any[]>([])
const dayTotal = ref(0)
const selectedActivityId = ref(0)
const quantity = ref(1)
const showActivity = ref(false)
const activityTitle = ref('')
const activityColumns = computed(() => activityTemplates.value.map((t: any) => ({ text: `${t.title} (${t.pointsPerUnit})`, value: t.id })))

// 使用 Asia/Shanghai 时区获取今天的日期
const today = computed(() => dayjs().tz('Asia/Shanghai').format('YYYY-MM-DD'))

onMounted(async () => {
  await children.load()
  await loadTemplates()
  await loadRecords()
})

async function loadTemplates() {
  const a = await $fetch('/api/activities/templates')
  activityTemplates.value = a.templates
}

async function loadRecords() {
  if (!children.currentChildId) return
  const res = await $fetch('/api/records', { params: { childId: children.currentChildId, date: today.value } })
  records.value = res.records
  dayTotal.value = res.dayTotal
}

function displayActivity(id: number) {
  return activityTemplates.value.find((t: any) => t.id === id)?.title || id
}

async function addRecord() {
  if (!children.currentChildId || !selectedActivityId.value) return
  await $fetch('/api/records', {
    method: 'POST',
    body: {
      childId: children.currentChildId,
      activityTemplateId: selectedActivityId.value,
      date: today.value,
      quantity: quantity.value
    }
  })
  quantity.value = 1
  selectedActivityId.value = 0
  activityTitle.value = ''
  await loadRecords()
  showToast('已添加记录')
}

async function removeRecord(id: number) {
  try {
    await showConfirmDialog({
      title: '确认删除',
      message: '删除后记录保留，但分数将从总分中扣除，确定要删除吗？',
      confirmButtonText: '确定删除',
      cancelButtonText: '取消'
    })

    // 用户确认后执行删除
    await $fetch(`/api/records/${id}`, { method: 'DELETE' })
    await loadRecords()
    showToast('已删除记录')
  } catch (error) {
    // 用户取消删除，不做任何操作
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

function onPickActivity({ selectedOptions }: any) {
  const opt = selectedOptions?.[0]
  if (opt) {
    selectedActivityId.value = opt.value
    activityTitle.value = opt.text
  }
  showActivity.value = false
}
</script>


